package net.esj.basic.translate.defaults;

import java.beans.PropertyDescriptor;

import net.esj.basic.core.engine.support.translator.AbstractTranslator;
import net.esj.basic.core.engine.support.translator.TranslateException;
import net.esj.basic.core.view.support.vojo.BaseVojo;
import net.esj.basic.core.view.support.vojo.TransObject;
import net.esj.basic.pojo.AbstractPojo;
import net.esj.basic.pojo.PrimaryKey;
import net.esj.basic.utils.ClassUtils;
import net.esj.basic.utils.Validators;

import org.hibernate.proxy.HibernateProxy;
import org.hibernate.proxy.LazyInitializer;

public class DefaultsPoAndVoTranslator extends AbstractTranslator {

	/**
	 * 先转HIBERNATE的代理 再递归转
	 */
	protected Object handleTransBeforeWrite(Object value,PropertyDescriptor targetPd,PropertyDescriptor sourcePd) throws TranslateException{
		Object reval = value;
		
		try{
			
			if(value instanceof HibernateProxy ){//如果为HIBERNATE的代理 1：已被初始化则继承 2：未初始化则新增且赋值ID
				LazyInitializer lazyInitializer = ((HibernateProxy)value).getHibernateLazyInitializer();
				if(Validators.isEmpty(lazyInitializer.getIdentifier())){//如果ID不存在，则该对象为NULL
					return null;
				}
				
				if(lazyInitializer.isUninitialized()) {//未初始化则只赋值ID
					if(BaseVojo.class.isAssignableFrom(targetPd.getPropertyType())){
						reval  = targetPd.getPropertyType().newInstance();
						((BaseVojo)reval).setId((String) lazyInitializer.getIdentifier());
					}else if(PrimaryKey.class.isAssignableFrom(targetPd.getPropertyType())){
						reval = sourcePd.getPropertyType().newInstance();
						((PrimaryKey)reval).setId((String) lazyInitializer.getIdentifier());
					}else{
						reval = lazyInitializer.getIdentifier();
					}
				}else{
					if(BaseVojo.class.isAssignableFrom(targetPd.getPropertyType())){
						reval = translate( lazyInitializer.getImplementation(), targetPd.getPropertyType());
					}else if(PrimaryKey.class.isAssignableFrom(targetPd.getPropertyType())){
						reval = lazyInitializer.getImplementation();
					}else{
						reval = lazyInitializer.getImplementation();
					}
				}
			}
			
			if(ClassUtils.isInterfaceOf(targetPd.getPropertyType(), TransObject.class)){
				reval = translate(value, targetPd.getPropertyType());
			}
		}catch(Throwable ex){
			throw new TranslateException(ex);
		}
		return reval;
	}
	
	
	@Override
	protected Object handleRetransBeforeWrite(Object value,
			PropertyDescriptor targetPd, PropertyDescriptor sourcePd)throws TranslateException {
		if( AbstractPojo.class.isAssignableFrom(targetPd.getPropertyType())
				&& TransObject.class.isAssignableFrom(sourcePd.getPropertyType())){
			Object v =  retrans(value, targetPd.getPropertyType());
			return v;
		}
		return value;
	}

}
